<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Controller;
use think\Db;
use Qiniu\Auth;

class  Base extends Controller {
    protected $_error;
    protected $_header;//用户的请求头信息
    protected $otherLogin  = '您的账号已在其他设备登录';
    protected $frost = '您的账号已被冻结';
    protected $del = '您的账号已被删除';

    // 构造函数
    public function __construct(){
        // 如果配置项为空 则直接返回
    }

    /**
     * 验证唯一——单点登录
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAll($uid,$time,$value,$reqKey){
        if($uid == 0) {
            return 111;
        } else {
            $user = Db::table('up_u_user')->where('user_id',$uid)->find();
            if($user['user_status'] == 2){ // 冻结
                return 110;
            }
            if($user['user_status'] == 3){ // 删除
                return 2111;
            }
//            $user = Db::table('up_u_user')->where('user_id', $uid)->find();
            $token = $user['user_token'];
            $appId = "A6070308312682";
            $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey) {
                return 112;
            } else {
                Db::table('up_u_user')->where('user_id',$uid)->setField('user_online',1);
                return 111;
            }
        }
    }
    public function rongyun($uid,$name,$imageurl){
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $uid = strval($uid);
        $body = "userId={$uid}&name={$name}&portraitUri={$imageurl}";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret.$nonce.$timeStamp);
        $header = array(
            'App-Key:'.$appKey,
            'Nonce:'.$nonce,
            'Timestamp:'.$timeStamp,
            'Signature:'.$sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/user/getToken.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
//    var_dump($res) ;
    }

    /**
     * formatTime 时间格式化
     * @param $time 时间戳
     * @return string
     */
    public function formatTime($time) {
        $now_time = time();
        $t = $now_time - $time;
        $yea = (int) ($t / (86400 * 30 * 12));
        if ($yea >= 1) {
            return $yea.'年前';
        }
        $mon = (int) ($t / (86400 * 30));
        if ($mon >= 1) {
            return '一个月前';
        }
        $day = (int) ($t / 86400);
        if ($day >= 1) {
            return $day . '天前';
        }
        $h = (int) ($t / 3600);
        if ($h >= 1) {
            return $h . '小时前';
        }
        $min = (int)($t / 60);
        if ($min >= 1) {
            return $min . '分钟前';
        }
        return '刚刚';
    }

    /**
     * 获取uuid
     * @param string $prefix
     * @return string
     */
    public function uuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid  = substr($chars,0,8);
        $uuid .= substr($chars,8,4);
        $uuid .= substr($chars,12,4);
        $uuid .= substr($chars,16,4);
        $uuid .= substr($chars,20,12);
        return $prefix . $uuid;
    }


    //---------------------------mabao--------------------------------
    public function isAssnLeader($user_id,$assn_id)
    {
        $member = Db::table('up_assn_member')
            ->where('am_user_id',$user_id)
            ->where('am_assn_id',$assn_id)
            ->where('am_user_type',2)
            ->find();
        if(!$member){
            $can = 0; // 0不可以编辑  1可以编辑
        }else{
            $can = 1;
        }
        return $can;
    }
    public function createGroupBefore($user_id)
    {
        $group = Db::table('up_friend_group')
            ->where('fg_user_id',$user_id)
            ->where('fg_name','默认分组')
            ->find();
        if(empty($group)){
            $res = Db::table('up_friend_group')->insertGetId([
                'fg_user_id' => $user_id,
                'fg_name' => '默认分组',
                'fg_auth' => 2,
                'fg_time' => date('Y-m-d H:i:s'),
            ]);
            if($res){
                return $res;
            }else{
                return false;
            }
        }else{
            return $group['fg_id'];
        }
    }
    //--------------------------------------------------融云群聊的操作------------------------------------------------
    //建群
    public function create($uids,$groupid,$name){
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $body = "{$uids}groupId=$groupid&groupName=$name";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/create.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }

    //加入
    /**
     * @return mixed
     */
    public function joinin($uidstr,$groupid,$name)
    {
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $body = "{$uidstr}groupId=$groupid&groupName=$name";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/join.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }

    //退出
    public function getout($uidstr,$groupid)
    {
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $body = "{$uidstr}groupId=$groupid";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/quit.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }
    //解散
    public function kill($uid,$groupid)
    {
        $appKey = config('rong.appKey');
        $appSecret = config('rong.appSecret');
        $body = "userId=$uid&groupId=$groupid";
        $nonce = mt_rand();
        $timeStamp = time();
        $sign = sha1($appSecret . $nonce . $timeStamp);
        $header = array(
            'App-Key:' . $appKey,
            'Nonce:' . $nonce,
            'Timestamp:' . $timeStamp,
            'Signature:' . $sign,
            'Content-Type: application/x-www-form-urlencoded'
        );
        $url = 'http://api.cn.ronghub.com/group/dismiss.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
//    curl_setopt($ch, CURLOPT_SSL_VERI/FYPEER, false);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        return $res;
    }
    //---------------------------mabao--------------------------------
    
    /**
     * 获取七牛token
     * @return string
     */
    public function getQiniuToken(){//echo 1;die;
        require_once ('../extend/qiniu/autoload.php');
        header("Access-Control-Allow-Origin:*");
        $accessKey = config('qiniu')['accessKey'];
        $secretKey = config('qiniu')['secretKey'];
        $bucket = config('qiniu')['bucket'];
//        $auth = new Qiniu();
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        return json_encode(array('data'=>$token));
    }
    
    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
//        $alias = (string)$alias;
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        return $push->send();
    }
    
    /**
     * 敏感词替换
     * @param $str
     */
    public function sensitive($str){
        $sensitiveList = Db::table('up_sensitive')->column('s_word');
        $leng = count($sensitiveList);
        if($leng > 0){
            for($i = 0; $i < $leng; $i++){
//                $word = $str;
                $is_have = stristr($str, $sensitiveList[$i]);
                if($is_have != false){
                    $str = str_ireplace($sensitiveList[$i], '***', $str);
                }
            }
        }
        return $str;
    }
    
    /**
     * 根据生日算年龄
     * @param $birthday
     * @return false|string
     */
    function getAge($birthday){
        $time = strtotime($birthday);//取得生日的时间戳
        $byear = date('Y', $time);//生日时间--年
        $bmonth = date('m', $time);//生日时间--月
        $bday = date('d', $time);//生日时间--日
        //初始化当前日期
        $nyear = date('Y');
        $nmonth = date('m');
        $nday = date('d');
        //计算年龄
        $age = $nyear - $byear;
        //如果当前时间的month小于生日的month，则年龄-1岁
        if($nmonth < $bmonth){
            $age = $age - 1;
            //如果当前时间的month等于生日的month，并且当前时间的day小于生日的day，则年龄-1
        }elseif($nmonth == $bmonth && $nday < $bday){
            $age = $age - 1;
        }
        return $age;
    }
}